angular.module('pop-up', [])

.service 'popUpSrv', ($q, $compile, $rootScope, $ionicBody, $ionicBackdrop, $ionicPopup) ->
    do: (items) ->
        scope = $rootScope.$new()
        scope.defer = $q.defer() # 传递到directive中
        scope.items = items # 传递到directive中

        template = '''
            <pop-up-item q='defer' items='items'></pop-up-item>
            '''
        linkFn = $compile template
        element = linkFn scope
        $ionicBackdrop.retain() # 背景遮照
        $ionicBody.get().appendChild element[0]
        callBack = (reason) ->
            element.children().removeClass('popup-on')
            element.children().addClass('popup-off')
            element.children()[0].addEventListener('webkitAnimationEnd',(->
                element.remove()
            ),false);
            $ionicBackdrop.release() # 取消背景遮照
        scope.defer.promise.then ((type) -> # 从directive成功返回
            element.children().removeClass('popup-on')
            element.children().addClass('popup-off')
            element.children()[0].addEventListener('webkitAnimationEnd',(->
                element.remove()
            ),false);
            setTimeout items[type].func,200

            callBack()
        ), callBack

# 不要直接使用这个directive，而是使用上面的shareService封装
.directive 'popUpItem', ($ionicScrollDelegate) ->
    restrict    : 'E'
    templateUrl : 'templates/pop-up/pop-up.html'
    scope:
        'defer' : '=q'
        'items' : '=items'
    link: ($scope, $element, $attrs) ->
        console.log "start",$element.children()
        document.getElementsByClassName('backdrop').item(0).addEventListener('click', ->$scope.cancel())
        $scope.choose = (idx) -> $scope.defer.resolve idx
        $scope.cancel = ->
#            $element[0].style.animation = 'popup-off 1s'
#            $element.find('popup').g.removeClass()
#            console.log $element.find('popup')[0].style.animation
            document.getElementsByClassName('backdrop').item(0).removeEventListener('click')
            $scope.defer.reject()
